package nafos.server

import org.slf4j.LoggerFactory
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit

/**
 * @Author 黄新宇
 * @Date 2018/8/6 上午11:57
 * @Description 协程计数管理，用作优雅关机的等待
 **/
object LatchCountManager {
    private val logger = LoggerFactory.getLogger(LatchCountManager::class.java)

    private val fixedThreadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2)


    fun start(method: () -> Unit) {
        fixedThreadPool.execute {
            method()
        }
    }

    fun <T> stateStart(any: T, threadLocal: ThreadLocal<T>, method: () -> Unit) {
        fixedThreadPool.execute {
            threadLocal.set(any)
            try {
                method()
            } catch (e: Exception) {
                logger.error(e.toString())
                threadLocal.remove()
            }
        }
    }


    fun waitOver(timeOutSeconds: Long) {
        fixedThreadPool.shutdown()
        if (!fixedThreadPool.awaitTermination(timeOutSeconds, TimeUnit.SECONDS)) {
            try {
                fixedThreadPool.shutdownNow()
            } catch (e: Exception) {
            }
            logger.info("======>>>>>>线程池强制中断<<<<<<======")
        }
        logger.info("======>>>>>>线程池运行结束<<<<<<======")
    }


}